import json, logging.handlers
import os

import pymysql
from bs4 import BeautifulSoup
from config import DIR_PATH


# 断言工具
def common_assert(response, status_code=None, description=None, text=None):
    if status_code:
        assert response.status_code == status_code, "状态码断言错误，预期状态码：{} != 实际状态码：{}".format(status_code,
                                                                                                           response.status_code)
    if description:
        assert description in response.json().get(
            "description"), "description断言错误，预期description：{} != 实际description：{}".format(description,
                                                                                                  response.json().get(
                                                                                                      "description"))
    if text:
        assert text in response.text, "text断言错误，预期text：{} != 实际text：{}".format(text, response.text)


# 读取json文件数据工具
def read_json_data(filename, key):
    filepath = DIR_PATH + "/data/" + filename
    list = []
    with open(filepath, encoding="utf-8") as f:
        for data in json.load(f).get(key):
            list.append(tuple(data.values())[1:])
    return list


# 日志工具
class GetLog:
    log = None

    @classmethod
    def get_log(cls):
        if cls.log is None:
            # 获取日志器
            cls.log = logging.getLogger()
            # 设置入口级别
            cls.log.setLevel(logging.INFO)
            # 设置文件
            filepath = DIR_PATH + os.sep + "log" + os.sep + "p2p.log"
            tf = logging.handlers.TimedRotatingFileHandler(filename=filepath, when="midnight", interval=1,
                                                           backupCount=3, encoding="utf-8")
            # 设置格式
            fm = "%(asctime)s %(levelname)s [%(filename)s(%(funcName)s:%(lineno)d)] - %(message)s"
            fmt = logging.Formatter(fm)

            # 将格式器添加到文件中
            tf.setFormatter(fmt)
            # 将文件添加到日志器中
            cls.log.addHandler(tf)
        return cls.log


def html_parser(result):
    html = result.json().get("description").get("form")
    bs = BeautifulSoup(html, "html.parser")
    url = bs.form.get("action")
    data = {}
    for input in bs.find_all("input"):
        data[input.get("name")] = input.get("value")
    return url, data


if __name__ == '__main__':
    GetLog.get_log().info("信息级别测试")
    GetLog.get_log().error("error级别测试")
# {
#     "desc": "注册成功",
#     "phone": "15037447717",
#     "password": "y123456",
#     "imgVerifyCode": 8888,
#     "phone_code": 666666,
#     "description": "成功"
# },
# {
#       "desc": "登录成功（锁定）",
#       "keywords": "15037447717",
#       "password": "error123456",
#       "description": "成功"
#     }
